<?php
// ========================== 文件说明 ==========================//
// 本文件说明：分类管理
// ==============================================================//


if(!defined('IN_ROOT') || !isset($php_self) || !preg_match("/[\/\\\\]index\.php$/", $php_self)) {
	exit('Access Denied');
}

//权限检查
//permission();

// 检查分类名是否符合逻辑
function checkname($name) {
	if(!$name || strlen($name) > 30) {
		$result = '分类名不能为空并且不能超过30个字符<br />';
		return $result;
	}
}

//添加分类

if($action == 'doaddcate') {
	$cate_title   = trim($_POST['name']);
	$cate_content   = trim($_POST['content']);
	$displayorder = intval($_POST['displayorder']);

	$result = checkname($cate_title);

	if($result) {

		redirect($result);

	}
	$cate_title = char_cv($cate_title);

    $rs = $db->fetch_one_array("SELECT count(*) AS categories FROM {$tablepre}xna_category WHERE cate_title='$cate_title'");

    if($rs['categories']) {

		redirect('该分类名在数据库中已存在');

    }

    $db->query("INSERT INTO {$tablepre}xna_category (cate_title,cate_content,displayorder) VALUES ('$cate_title','$cate_content','$displayorder')");
	$db->query("UPDATE {$tablepre}xna_statistics SET cate_count=cate_count+1");
	categories_recache();
	statistics_recache();

    redirect('添加新分类成功', 'index.php?job=category');

}


//修改分类

if($action == 'domodcate') {
	$cate_title   = trim($_POST['name']);
	$cate_content   = trim($_POST['content']);
	$cid    = intval($_POST['cid']);
	$result = checkname($name);

	if($result)	{redirect($result);}

	$name = char_cv($name);
	$rs = $db->fetch_one_array("SELECT count(*) AS categories FROM {$tablepre}xna_category WHERE cid!='$cid' AND cate_title='$name'");
    if($rs['categories']) {
		redirect('已经有其他分类使用【'.$name.'】这个名称');
    }

	// 更新分类

    $db->query("UPDATE {$tablepre}xna_category SET cate_title='$name',cate_content='$cate_content' WHERE cid='$cid'");

	categories_recache();

    redirect('修改分类成功', 'index.php?job=category');
}


//删除分类
if($action == 'dodelcate') {
	$cid = intval($_POST['cid']);
	$aids = $a_tatol = 0;

	// 删除分类

	$db->query("DELETE FROM {$tablepre}xna_category WHERE cid='$cid'");

	/*$query = $db->query("SELECT feedid, keywords, uid, state FROM {$tablepre}xna_site WHERE cid='$cid' ORDER BY id");

	while ($article = $db->row($query)) {
		$aids .= ','.$article['feedid'];
		if ($article['keywords']) {
			updatetags($article['feedid'], '', $article['keywords']);
		}
		if ($article['state']) {
			$a_tatol++;
			$db->query("UPDATE {$tablepre}users SET xna_site=xna_site-1 WHERE userid='".$article['uid']."'");
		}
	}*///end while

    redirect('成功删除分类', 'index.php?job=category');

}

//修改Tag
if($action == 'domodtag') {
	$newitem = addslashes($_POST['tag']);
	$olditem = addslashes($_POST['oldtag']);
	$tagid   = intval($_POST['tagid']);
	$result  = checktag($newitem);
	if($result)	{
		redirect($result);
	}
    $result = $db->num($db->query("SELECT tagid FROM {$tablepre}xna_tags WHERE tag='$newitem'"));
    if($result) {
        redirect('数据库中已存在相同的数据', 'index.php?job=category&action=modtag&tagid='.$tagid);
    }
	$tag = $db->fetch_one_array("SELECT aids FROM {$tablepre}xna_tags WHERE tag='$olditem'");
	if ($tag) {
		$query  = $db->query("SELECT siteid, keywords FROM {$tablepre}xna_site WHERE siteid IN (".$tag['aids'].")");
		while ($article = $db->row($query)) {
			$newtag = str_replace($olditem, $newitem, $article['keywords']);
			$db->query("UPDATE {$tablepre}xna_site SET keywords='".addslashes($newtag)."' WHERE articleid='".$article['articleid']."'");
		}
		$db->query("UPDATE {$tablepre}xna_tags SET tag='$newitem' WHERE tagid='$tagid'");
	}
	hottags_recache();
    redirect('修改Tags成功', 'index.php?job=category&action=taglist');
}

//批量删除Tag
if($action == 'dodeltag') {
    if (!$_POST['tag'] || !is_array($_POST['tag'])) {
        redirect('未选择任何Tags');
    }
	$tag_count=0;
	foreach ($tag as $name => $id) {
		removetag($name, $id);
		$tag_count++;
	}
	$db->query("UPDATE {$tablepre}statistics SET tag_count=tag_count-".$tag_count);
	hottags_recache();
	statistics_recache();
    redirect('成功删除所选Tags', 'index.php?job=category&action=taglist');
}

//清理Tags
if ($action == 'dotagclear') {
	//清空Tags表
	if (!$step) {
		$db->query("TRUNCATE TABLE {$tablepre}xna_tags");
	    $step=1;
	}
	$percount = ($percount <= 0) ? 100 : $percount;
	$start    = ($step - 1) * $percount;
	$next     = $start + $percount;
	$step++;
	$jumpurl  = 'index.php?job=category&action=dotagclear&step='.$step.'&percount='.$percount;
	$goon     = 0;
	$query    = $db->query("SELECT siteid, keywords FROM {$tablepre}xna_site WHERE visible='1' ORDER BY siteid LIMIT $start, $percount");
	while($article = $db->row($query)){
		$goon = 1;
		if ($article['keywords']) {
			$tagdb = explode(',', $article['keywords']);
			$tagnum = count($tagdb);
			for($i=0; $i<$tagnum; $i++) {
				$tagdb[$i] = trim($tagdb[$i]);
				if ($tagdb[$i]) {
					$tag  = $db->fetch_one_array("SELECT tagid,aids FROM {$tablepre}xna_tags WHERE tag='$tagdb[$i]'");
					if(!$tag) {
						$db->query("INSERT INTO {$tablepre}xna_tags (tag,usenum,aids) VALUES ('$tagdb[$i]', '1', '".$article['articleid']."')");
					} else {						
						$aids = $tag['aids'].','.$article['articleid'];
						$db->query("UPDATE {$tablepre}xna_tags SET usenum=usenum+1, aids='$aids' WHERE tag='$tagdb[$i]'");
					}
				}
				unset($aids);
			}
		}
	}
	if($goon){
		redirect('正在更新 '.$start.' 到 '.$next.' 项', $jumpurl, '2');
	} else{
		$tag_count = $db->num($db->query("SELECT tagid FROM {$tablepre}xna_tags"));
		$db->query("UPDATE {$tablepre}xna_statistics SET tag_count='$tag_count'");
		hottags_recache();
		statistics_recache();
		redirect('成功执行清理操作', 'index.php?job=category&action=taglist');
	}
}

// 更新分类排序
if ($action == 'updatedisplayorder') {
	if (!$_POST['displayorder'] || !is_array($_POST['displayorder'])) {
		redirect('未选择任何分类');
	}

	foreach($displayorder as $cid => $order) {

		$db->query("UPDATE {$tablepre}xna_category SET displayorder='".intval($order)."' WHERE cid='$cid'");

	}
	categories_recache();
	redirect('所有分类的排序已更新', 'index.php?job=category');
}

if(!$action) {
	$action = 'catelist';
}

//分类列表

if ($action == 'catelist') {
	$catedb = array();
	$query = $db->query("SELECT * FROM {$tablepre}xna_category ORDER BY displayorder ASC");
	$tatol = $db->num($query);
	while($cate = $db->row($query)){
		$catedb[] = $cate;
	}
	unset($cate);
	$db->free($query);
	$subnav = '分类管理';
}

//分类操作
if (in_array($action, array('addcate', 'modcate', 'delcate'))) {
	if ($action == 'addcate') {
		$subnav = '添加分类';
        $cate["cid"]=intval($_GET['cid']);
	} else {
		$cate = $db->fetch_one_array("SELECT * FROM {$tablepre}xna_category WHERE cid='".intval($_GET['cid'])."'");
		if($action == 'modcate') {
			$subnav = '修改分类';
		} else {
			$subnav = '删除分类';
		}
	}
}
//标签列表

if (in_array($action, array('taglist', 'getalltags'))) {
	if($action == 'taglist') {
		$order = $_GET['ordered'] == 'usenum' ? 'usenum' : 'tagid';
		if($page) {
			$start_limit = ($page - 1) * 30;
		} else {
			$start_limit = 0;
			$page = 1;
		}
		$numsql = "LIMIT $start_limit, 30";
		$rs = $db->fetch_one_array("SELECT count(*) AS tags FROM {$tablepre}xna_tags");
		$tatol = $rs['tags'];
		$multipage = multi($tatol, 30, $page, 'index.php?job=category&action=taglist');
	} else {
		$order = 'tagid';
		$numsql = '';
	}
    $query = $db->query("SELECT tagid,tag,usenum FROM {$tablepre}xna_tags ORDER BY $order DESC $numsql");
	$tagdb = array();
    while ($tag = $db->row($query)) {
		$tag['url'] = urlencode($tag['tag']);
		$tag['item'] = htmlspecialchars($tag['tag']);
		$tagdb[] = $tag;
	}
	unset($tag);
	$db->free($query);

	if($action == 'taglist') {
		$subnav = '全部标签';
	} else {
		include PrintEot('getalltags');
		PageEnd();
	}
}//list

//修改标签
if($action == 'modtag') {
	$tagid = intval($_GET['tagid']);
	$taginfo = $db->fetch_one_array("SELECT tagid,tag,usenum,aids FROM {$tablepre}xna_tags WHERE tagid='$tagid'");
	if ($taginfo) {
		$taginfo['item'] = htmlspecialchars($taginfo['tag']);
		$query  = $db->query("SELECT siteid, title FROM {$tablepre}xna_site WHERE siteid IN (".$taginfo['aids'].")");
		$articledb = array();
		while ($article = $db->row($query)) {
			$articledb[] = $article;
		}
		unset($article);
		$db->free($query);
	}
	$subnav = '修改标签';
}//mod

//标签清理
if($action == 'tagclear') {
	$subnav = '标签清理';
}

if (strstr($action, 'tag')) {
	$catenav = '标签管理';
	$cateurl = 'taglist';
} else {
	$catenav = '分类管理';
	$cateurl = 'catelist';
}

$navlink_L = ' &raquo; <a href="index.php?job=category&action='.$cateurl.'">'.$catenav.'</a>'.($subnav ? ' &raquo; '.$subnav : '');
cpheader();
include template("category", _ROOT . "/template/admin/");
?>